package main

import (
	zimgio "wisdom_education_in_kunshan/image"
	"wisdom_education_in_kunshan/image/threshold"
)

// SavePNG save  imgPath->savePath
func SavePNG(imgPath, savePath string) error {
	i, err := zimgio.Read(imgPath)
	if err != nil {
		return err
	}
	err = i.SaveAsPNG(savePath)
	if err != nil {
		return err
	}
	return nil
}

// Translate 验证码处理
func Translate(imgPath, savePath string) error {
	i, err := zimgio.Read(imgPath)
	if err != nil {
		return err
	}
	// i.DGraying()
	tImage := threshold.TImage{i, nil}
	t := tImage.ByOSTU()
	i = tImage.Binaryzation(t)
	dAcnode(i)
	dc(i)
	err = i.SaveAsPNG(savePath)
	if err != nil {
		return err
	}
	return nil
}

func dc(img *zimgio.Image) {
	for x, col := range img.RGBA {
		for y, v := range col {
			if x <= 4 || y <= 2 || x >= 52 || y >= 16 {
				v.R = 0xFF
				v.G = 0xFF
				v.B = 0xFF
			}
		}
	}
}

func dAcnode(img *zimgio.Image) {
	for x, col := range img.RGBA {
		for y, v := range col {
			if v.R == 0 {
				handleEdges(img, x, y)
			} else {
				if findEdgeNum(img, x, y) == 4 {
					v.R = 0
					v.G = 0
					v.B = 0
				}
			}
		}
	}
}

func handleEdges(img *zimgio.Image, x int, y int) {
	w := img.Width
	h := img.Height
	num := 0
	var ex, ey int
	if x > 1 && img.RGBA[x-1][y].R == 0 {
		num += 1
		ex = x - 1
		ey = y
	}
	if x < w-1 && img.RGBA[x+1][y].R == 0 {
		num += 1
		ex = x + 1
		ey = y
	}
	if y > 1 && img.RGBA[x][y-1].R == 0 {
		num += 1
		ex = x
		ey = y - 1
	}
	if y < h-1 && img.RGBA[x][y+1].R == 0 {
		num += 1
		ex = x
		ey = y + 1
	}
	switch num {
	case 0:
		img.RGBA[x][y].R = 0xFF
		img.RGBA[x][y].G = 0xFF
		img.RGBA[x][y].B = 0xFF
		break
	case 1:
		if findEdgeNum(img, ex, ey) <= 1 {
			img.RGBA[x][y].R = 0xFF
			img.RGBA[x][y].G = 0xFF
			img.RGBA[x][y].B = 0xFF
			////////////////////////
			img.RGBA[ex][ey].R = 0xFF
			img.RGBA[ex][ey].G = 0xFF
			img.RGBA[ex][ey].B = 0xFF
		}
		break
	default:
		break
	}
}

func findEdgeNum(img *zimgio.Image, x int, y int) int {
	w := img.Width
	h := img.Height
	num := 0
	if x > 1 && img.RGBA[x-1][y].R == 0 {
		num += 1
	}
	if x < w-1 && img.RGBA[x+1][y].R == 0 {
		num += 1
	}
	if y > 1 && img.RGBA[x][y-1].R == 0 {
		num += 1
	}
	if y < h-1 && img.RGBA[x][y+1].R == 0 {
		num += 1
	}
	return num
}
